/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "ParticleRendering.h"
#include "../Managers/DX11Manager.h"
#include "../Components/ParticleSystem.h"
#include "../Directors/DX11Director.h"

#include "../Components/PointLight.h"

#include <algorithm>


namespace Hogshead
{
	namespace DX11Rendering
	{
		DirectorCPP(Hogshead::DX11Rendering::ParticleRendering)

		ParticleRendering::ParticleRendering(void)
		{
		}


		ParticleRendering::~ParticleRendering(void)
		{
		}

		void ParticleRendering::initialize()
		{
			_current_vs = 0;
			_current_gs = 0;
			_current_ps = 0;
			_light_error = Color(1.0f,0,0);
			_prev_game_time = 0.0f;
			this->_enabled = true;
		}

		void ParticleRendering::finalize()
		{
			
		}

		void ParticleRendering::update(const GameTimer& in_gt)
		{
			
			float delta = in_gt.getUpdateDelta();
			/*DX11Manager::_game_info_struct._time_step = delta;
			DX11Manager::_game_info_struct._game_time = in_gt.getGameTime();*/
			_prev_game_time = in_gt.getGameTime();

			//DX11Manager::updateConstantBuffer(GAME_INFO, &DX11Manager::_game_info_struct);

		}

		void ParticleRendering::registerComponent(IComponent* in_component)
		{
			if(in_component->is<ParticleSystem>())
			{
				ParticleSystem* ps = in_component->as<ParticleSystem>();
				if(!ps->_alpha_blended)
					_registered_components.add(in_component);
			}
			else if(in_component->is<PointLight>())
			{
				_point_lights.add(in_component->as<PointLight>());
			}
		}

		void ParticleRendering::render(Camera* in_active_camera)
		{
			//DX11Manager::setRenderTargets(1, &(*in_render_targets)[DX11Director::BACK_BUFFER]->first, DX11Manager::_depth_stencil_view);
			//DX11Manager::_basic_dynamic_struct._view = in_active_camera->getView();

			//DX11Manager::_basic_dynamic_struct._eye = Vector4(in_active_camera->getParentGameObject()->getTransform().getWorldPosition(),0.0f);

			//Vector3 cam_forward = in_active_camera->getForward();
			//DX11Manager::_game_info_struct._cam_forward = Vector4(in_active_camera->getForward(),0.0f);
			//DX11Manager::_game_info_struct._cam_right = Vector4(in_active_camera->getRight(),0.0f);
			//DX11Manager::_game_info_struct._cam_up = Vector4(in_active_camera->getUp(),0.0f);

			////rebind the constant buffers
			//for( int i = 0; i < _cBuffer_count; i++ )
			//{
			//	 DX11Manager::bindConstantBuffer( &DX11Manager::_constant_buffers[i], (UINT)i, VGP );
			//}

			//DX11Manager::updateConstantBuffer(GAME_INFO, &DX11Manager::_game_info_struct);

			//------------------------------------------
			//Particle Rendering
			//------------------------------------------
			//for(int i = 0; i < _registered_components.size(); i++)
			//{
			//	
			//	ParticleSystem* cur_system = _registered_components[i]->as<ParticleSystem>();

			//	
			//	//set our world matrix
			//	Matrix4 world =  cur_system->getParentGameObject()->getTransform().getWorldMatrix();
			//	DX11Manager::_basic_dynamic_struct._world = world;
			//					
			//	DX11Manager::updateConstantBuffer(BASIC_DYNAMIC,  (const void*)(&DX11Manager::_basic_dynamic_struct));

			//	DX11ParticleInfo* render_info = cur_system->getRenderInfo()->as<DX11ParticleInfo>();
			//	//render_info->_particle_info._spawn_position_range = render_info->_particle_info._spawn_position_range + 
			//	//	Vector4(cur_system->getParentGameObject()->getTransform()->getWorldPosition(),0);

			//	DX11Manager::updateConstantBuffer(PARTICLE_INFO, (const void*)(&render_info->_particle_info));
			//		
			//	//DX11Manager::setInputLayout(render_info->_material->_vs->_input_layout->_input_layout);
			//	DX11Manager::setSamplers(0,1,&render_info->_material->_sampler_state->_sampler_state,PS);
			//	DX11Manager::setSamplers(0,1,&render_info->_material->_sampler_state->_sampler_state,GS);
			//	DX11Manager::setTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
			//	DX11Manager::setDepthStencilState(false, D3D11_DEPTH_WRITE_MASK_ZERO, D3D11_COMPARISON_LESS);

			//	////set our textures
			//	if(render_info->_particle_texture)
			//		DX11Manager::setPSShaderResource(0, &render_info->_particle_texture->_shader_resource_view);
			//	DX11Manager::setGSShaderResource(1, &render_info->_random_texture_view);

			//	//-----------------------------------
			//	//first we create and kill particles
			//	//-----------------------------------
			//	if(render_info->_first_run)
			//	{
			//		DX11Manager::setVertexBuffer(render_info->_init_buffer_VB, sizeof(Particle));
			//	}
			//	else
			//	{
			//		DX11Manager::setVertexBuffer(render_info->_draw_VB, sizeof(Particle));
			//	}


			//	DX11Manager::setSOTargets(1, &render_info->_stream_out_VB);

			//	DX11Manager::setShaders(render_info->_creation_vs->_vs, render_info->_creation_gs->_gs, NULL);
			//	
			//	DX11Manager::setSamplers(0,1,&render_info->_material->_sampler_state->_sampler_state,PS);
			//	DX11Manager::setSamplers(0,1,&render_info->_material->_sampler_state->_sampler_state,GS);
			//	if(render_info->_first_run)
			//	{
			//		DX11Manager::draw(render_info->_num_emitters, 0);
			//		render_info->_first_run = false;
			//	}
			//	else
			//	{
			//		DX11Manager::drawAuto();
			//	}

			//	//unbind the vertex buffer from the stream output
			//	ID3D11Buffer* null_buffer[1] = {0};
			//	DX11Manager::setSOTargets(1, null_buffer);

			//	//ping pong the vertex buffers
			//	std::swap(render_info->_draw_VB, render_info->_stream_out_VB);

			//	//draw the particle system
			//	DX11Manager::setVertexBuffer(render_info->_draw_VB, sizeof(Particle));
			//	DX11Manager::setRasterizerState(render_info->_material->_rasterizer_state->_rasterizer_state);
			//	DX11Manager::setShaders(render_info->_material->_vs->_vs, render_info->_material->_gs->_gs, render_info->_material->_ps->_ps);
			//	DX11Manager::setBlendState(render_info->_material->_blend_state->_blend_state, NULL, 0xffffffff);
			//	DX11Manager::setDepthStencilState(true, D3D11_DEPTH_WRITE_MASK_ZERO, D3D11_COMPARISON_LESS);
			//		
			//	DX11Manager::drawAuto();

			//}
		}


		float ParticleRendering::calcAttenuation(float in_light_distance, float in_light_attenuation)
		{
			float att = in_light_attenuation * in_light_distance;
			return att * att;
		}

		//int ParticleRendering::setLights(IComponent* in_component)
		//{
			
			/*IRenderInfo* render_info = in_component->getRenderInfo(); 
			StaticMesh* current_mesh = NULL;
			if(render_info->is<DX11StaticMeshInfo>())
			{
				current_mesh = render_info->as<DX11StaticMeshInfo>()->_object_to_render;
			

				DX11Manager::_basic_dynamic_struct._ambient_color = current_mesh->_material->_ambient_light;

				_active_lights.clear();

				for(int i = 0; i < _point_lights.size(); i++)
				{		
					float distance_to_light = Vector3::distance(_point_lights.get(i)->getParentGameObject()->getTransform()->getWorldPosition(), in_component->getParentGameObject()->getTransform()->getWorldPosition());
					distance_to_light -= current_mesh->_material->_light_activate_distance;
					distance_to_light = Math::max(distance_to_light, 0.0f);
					if( this->calcAttenuation(distance_to_light, _point_lights[i]->_attenuation_parameter) < 1.0f)
					{		
						_active_lights.add(Pair<float, PointLight*>(distance_to_light,_point_lights[i]));
					}
				}
			

				for(int i = 0; i < 4; i++)
				{
					DX11Manager::_diffuse_dynamic_struct._light_color[i] = Color::Black();
					DX11Manager::_diffuse_dynamic_struct._light_pos[i] = Vector4(0,0,0,0);
					DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(0,0,0,0);
					DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(0,0,0,0);
				}

				if(_active_lights.size() > 4)
				{
					StringBuilder sb;
					sb << "ERROR IN LIGHTING: More than 4 point lights affect single object" << endl;
					sb << "\tObject Affected: " << endl;
					sb << "\tObject Name: " << in_component->getParentGameObject()->_global_name << endl;
					sb << "\tObject Position: " << in_component->getParentGameObject()->getTransform()->getWorldPosition() << endl;
					sb << endl;

					DX11Manager::_basic_dynamic_struct._ambient_color = _light_error;
					for(int i = 0; i < 4; i++)
					{
						DX11Manager::_diffuse_dynamic_struct._light_color[i] = _light_error;
						Vector4 light_pos = _active_lights[i].second->getPosition();
						DX11Manager::_diffuse_dynamic_struct._light_pos[i] = light_pos;
						DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(_active_lights[i].second->_attenuation_parameter, 0,0,0);
						DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(current_mesh->_material->_max_specular,0,0,0);
					}

	#ifdef _DEBUG
					for(int i = 0; i < _active_lights.size(); i++)
					{
						PointLight* cur_light = _active_lights[i].second;
						sb << "\tLight Name: " << cur_light->componentName() << endl;
						sb << "\tLight Position: " << cur_light->getParentGameObject()->getTransform()->getWorldPosition() << endl;
						sb << "\tLight Color: " << cur_light->_light_color._red << ", " << cur_light->_light_color._blue << ", " << cur_light->_light_color._green << endl;
						sb << endl;
					}
					DX11Manager::_logger->write(sb);
					hout << sb;
	#endif
				}
				else
				{
					for(int i = 0; i < _active_lights.size() && i < 4; i++)
					{
						DX11Manager::_diffuse_dynamic_struct._light_color[i] = (_active_lights[i].second->_light_color);
						Vector4 light_pos = _active_lights[i].second->getPosition();
						DX11Manager::_diffuse_dynamic_struct._light_pos[i] = light_pos;
						DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(_active_lights[i].second->_attenuation_parameter,0,0,0);
						DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(current_mesh->_material->_max_specular,0,0,0);
					}
				}
			}*/
			//return _active_lights.size();
		//}
	}
}